package com.talking.view;

import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import com.github.dhaval2404.imagepicker.ImagePicker;
import com.talking.App;
import com.talking.R;
import com.talking.adapter.WriteMomentPicAdapter;
import com.talking.bean.WriteMomentPicBean;
import com.talking.databinding.ActivityWriteMomentBinding;
import com.talking.presenter.MomentPresenter;
import com.talking.utils.Utils;

import org.jetbrains.annotations.NotNull;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class WriteMomentActivity extends AppCompatActivity {
    private ActivityWriteMomentBinding binding;
    private WriteMomentPicAdapter adp;
    private final List<WriteMomentPicBean> data=new ArrayList<>();
    private int nowPosition=0;
    private ActivityResultLauncher<Intent> launcher;
    @RequiresApi(api = Build.VERSION_CODES.O)
    @Override
    protected void onCreate(@Nullable @org.jetbrains.annotations.Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding= ActivityWriteMomentBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        Objects.requireNonNull(getSupportActionBar()).setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setHomeButtonEnabled(true);
        adp=new WriteMomentPicAdapter(this,data);
        binding.writeGrid.setOnItemClickListener((parent, view, position, id) -> {
            WriteMomentPicBean bean = data.get(position);
            nowPosition=position;
            if (bean.isAdd){
                ImagePicker.with(this).cropSquare().compress(1024).maxResultSize(1080, 1080).createIntent(intent -> {
                    launcher.launch(intent);
                    return null;
                });
            }else {
                AlertDialog.Builder dialog=new AlertDialog.Builder(this);
                dialog.setTitle("提示").setMessage("是否删除图片?").setPositiveButton("确定", (dialog1, which) -> {
                    File file=new File(bean.pictureUrl);
                    if (file.exists())file.delete();
                    data.remove(position);
                    adp.notifyDataSetChanged();
                }).setNeutralButton("取消",null).show();
            }
        });
        data.add(new WriteMomentPicBean(R.drawable.add2,true));
        binding.writeGrid.setAdapter(adp);
        launcher=registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), result -> {
            if (result.getResultCode() == RESULT_OK) {
                File origin = new File(result.getData().getData().getPath());
                File destination=new File(WriteMomentActivity.this.getExternalCacheDir(), "/"+origin.getName());
                try {
                    Files.copy(origin.toPath(),destination.toPath());
                } catch (IOException e) {
                    e.printStackTrace();
                }
                data.remove(nowPosition);
                data.add(new WriteMomentPicBean(destination.getAbsolutePath(),false));
                data.add(new WriteMomentPicBean(R.drawable.add2,true));
                adp.notifyDataSetChanged();
            } else if (result.getResultCode() == ImagePicker.RESULT_ERROR) {
                Utils.toast(ImagePicker.getError(result.getData()));
            }
        });
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_write_moment, menu);
        return true;
    }
    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        if (item.getItemId()== R.id.menu_write_moment){
            List<String>filelist=new ArrayList<>();
            for (WriteMomentPicBean writeMomentPicBean :data) {
                if (writeMomentPicBean.pictureUrl!=null){
                    filelist.add(writeMomentPicBean.pictureUrl);
                }
            }
            Utils.toast( "正在上传");
            MomentPresenter.uploadFiles("moment/uploadFiles/?content=" + binding.writeEdit.getText().toString()+"&account="+ App.sp.getString("account",""), filelist, new Callback() {
                @Override
                public void onFailure(@NotNull Call call, @NotNull IOException e) {
                    e.printStackTrace();
                }
                @Override
                public void onResponse(@NotNull Call call, @NotNull Response response) {
                    runOnUiThread(() -> {
                        try {
                            String result = response.body().string();
                            if (result.equals("上传完成")){
                                Utils.toast( result);
                                for (String s :filelist) {
                                    new File(s).delete();
                                }
                                finish();
                            }else {
                                Utils.toast( "上传错误"+result);
                            }
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    });
                }
            });
        }
        if (android.R.id.home==item.getItemId()){ finish(); }
        return true;
    }
}